package v1

import (
	bc "application/blockchain"
	"application/pkg/app"
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type Item struct {
	Poster      string  `json:"poster"`      // 发起人id
	Taker       string  `json:"taker"`       // 捐赠者id
	PosterImg   string  `json:"posterImg"`   // 发起人附加图片
	TakerImg    string  `json:"takerImg"`    // 捐赠|购买者附加图片
	Title       string  `json:"title"`       // 需求|销售标题
	Description string  `json:"description"` // 描述
	Price       float64 `json:"price"`       // 价格或等价标准
	Option      bool    `json:"option"`      //false~>DemandItem  true~>SaleItem
}

func CreateItem(c *gin.Context) {
	appG := app.Gin{C: c}
	body := new(Item)
	//解析Body参数
	if err := c.ShouldBind(body); err != nil {
		appG.Response(http.StatusBadRequest, "失败", fmt.Sprintf("参数出错%s", err.Error()))
		return
	}
	if body.Poster == "" || body.Title == "" || body.Price < 0 {
		appG.Response(http.StatusBadRequest, "失败", "标题不能为空，价格或等价标准不能为负")
		return
	}
	var bodyBytes [][]byte
	bodyBytes = append(bodyBytes, []byte(body.Poster))
	bodyBytes = append(bodyBytes, []byte(body.Taker))
	bodyBytes = append(bodyBytes, []byte(body.PosterImg))
	bodyBytes = append(bodyBytes, []byte(body.TakerImg))
	bodyBytes = append(bodyBytes, []byte(body.Title))
	bodyBytes = append(bodyBytes, []byte(body.Description))
	bodyBytes = append(bodyBytes, []byte(strconv.FormatFloat(body.Price, 'E', -1, 64)))
	bodyBytes = append(bodyBytes, []byte(strconv.FormatBool(body.Option)))
	// bodyBytes = append(bodyBytes, []byte(strconv.FormatFloat(body.LivingSpace, 'E', -1, 64)))
	//调用智能合约
	resp, err := bc.ChannelExecute("createItem", bodyBytes)
	if err != nil {
		appG.Response(http.StatusInternalServerError, "失败", err.Error())
		return
	}
	var data map[string]interface{}
	if err = json.Unmarshal(bytes.NewBuffer(resp.Payload).Bytes(), &data); err != nil {
		appG.Response(http.StatusInternalServerError, "失败", err.Error())
		return
	}
	appG.Response(http.StatusOK, "成功", data)
}

func QueryItem(c *gin.Context) {
	appG := app.Gin{C: c}
	body := new(Item)
	//解析Body参数
	if err := c.ShouldBind(body); err != nil {
		appG.Response(http.StatusBadRequest, "失败", fmt.Sprintf("参数出错%s", err.Error()))
		return
	}
	var bodyBytes [][]byte 
	if body.Poster != "" {
		bodyBytes = append(bodyBytes, []byte(body.Poster))
	}
	//调用智能合约
	resp, err := bc.ChannelQuery("queryItem", bodyBytes)
	if err != nil {
		appG.Response(http.StatusInternalServerError, "失败", err.Error())
		return
	}
	// 反序列化json
	var data []map[string]interface{}
	if err = json.Unmarshal(bytes.NewBuffer(resp.Payload).Bytes(), &data); err != nil {
		appG.Response(http.StatusInternalServerError, "失败", err.Error())
		return
	}

	appG.Response(http.StatusOK, "成功", data)
}
